/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.service;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import com.thinkgem.jeesite.common.utils.EnumProperty;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.bus.entity.Vaccine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.modules.sys.dao.AttachmentDao;
import com.thinkgem.jeesite.modules.sys.entity.Attachment;

/**
 * 附件信息Service
 * @author wzl
 * @version 2018-10-12
 */
@Service
@Transactional(readOnly = true)
public class AttachmentService extends CrudService<AttachmentDao, Attachment> {
	private ResourceBundle conf = ResourceBundle.getBundle("jeesite");
	private long allowSize = Long.parseLong(conf.getString("web.maxUploadSize"));// 允许文件大小
	private String fileName;
	private String[] fileNames;
	@Autowired
	private AttachmentDao attachmentDao;

	public ResourceBundle getConf() {
		return conf;
	}

	public void setConf(ResourceBundle conf) {
		this.conf = conf;
	}

	public long getAllowSize() {
		return allowSize;
	}

	public void setAllowSize(long allowSize) {
		this.allowSize = allowSize;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String[] getFileNames() {
		return fileNames;
	}

	public void setFileNames(String[] fileNames) {
		this.fileNames = fileNames;
	}

	private String getFileNameNew() {
		SimpleDateFormat fmt = new SimpleDateFormat("HHmmssSSS");
		return fmt.format(new Date());
	}

	public Attachment get(String id) {
		return super.get(id);
	}
	
	public List<Attachment> findList(Attachment attachment) {
		return super.findList(attachment);
	}
	
	public Page<Attachment> findPage(Page<Attachment> page, Attachment attachment) {
		return super.findPage(page, attachment);
	}
	
	@Transactional(readOnly = false)
	public void save(Attachment attachment) {
		super.save(attachment);
	}
	
	@Transactional(readOnly = false)
	public void delete(Attachment attachment) {
		super.delete(attachment);
	}

	/**
	 * @Author zhangxingliang
	 * @Description 删除七牛云上的文件
	 * @Date 14:14 2019/6/11
	 * @Param [attachment]
	 * @return void
	 **/
	@Transactional(readOnly = false)
	public void deleteQiniu(Attachment attachment) {
		//删除对应的七牛云上的图片，此图片在系统内是否被占用
		if(0 == this.attachmentDao.getAttachmentCntByFileName(attachment)){
			Configuration cfg = new Configuration(Zone.zone1());
			String accessKey = Global.getConfig("accessKey");
			String secretKey = Global.getConfig("secretKey");
			String bucket = Global.getConfig("bucket");
			String key = attachment.getFilePath();
			Auth auth = Auth.create(accessKey, secretKey);
			BucketManager bucketManager = new BucketManager(auth, cfg);
			try {
				bucketManager.delete(bucket, key);
			} catch (QiniuException ex) {
				System.err.println(ex.code());
				System.err.println(ex.response.toString());
			}
		};
		super.delete(attachment);
	}

	/**
	 * 
	 * @Title: uploadFile
	 * @author: wzl
	 * @date: 2018年10月20日 下午1:22:23
	 * @Description: 上传附件
	 * @param: file
	 * @return: Attachment
	 * @throws:
	 */
	@Transactional(readOnly = false)
	public Attachment uploadFile(MultipartFile file) throws Exception {
		
		if (file == null) {
			throw new Exception("上传失败：文件为空");    
		}
		if(file.getSize() > 10000000) {
			throw new Exception("上传失败：文件大小不能超过10M");            
		}
		String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).trim().toLowerCase();
		String name = String.valueOf(new Date().getTime()) + "." + suffix;
		if(file.getSize() > 0){
			String rootPath = Global.getConfig("filePath") + File.separator + "wildGoose" + File.separator + "ent_info";
			// 获取到图片在本地处理
			File targetFile = new File(rootPath, name);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 通过谷歌的工具压缩图片
//			CompressImgUtil.googleCompress(targetFile.getAbsolutePath(), targetFile.getAbsolutePath());
		} else {
			throw new Exception("上传失败：上传文件不能为空");
		}
		
		Attachment attachment = new Attachment();
		attachment.setFileName(name);
		attachment.setFileSize(String.valueOf(file.getSize()));
		attachment.setFileType(file.getContentType());
		attachment.setFilePath(File.separator + "wildGoose" + File.separator + "ent_info" + File.separator + name);
		this.save(attachment);
		return attachment;
	}

	 
	/**
	 * 
	 * @Title: findListByTable
	 * @author: wzl
	 * @date: 2018年10月22日 上午10:53:05
	 * @Description: 查询附件列表信息
	 * @param: tableName
	 * @param: tableId
	 * @return: List<Attachment>
	 * @throws:
	 */
	public List<Attachment> findListByTable(String tableId, String tableName) {
		Attachment attachment = new Attachment();
		attachment.setTableId(tableId);
		attachment.setTableName(tableName);
		return this.findList(attachment);
	}
	
	/**
	 * 
	 * @Title: uploadPenImg 
	 * @author: qjc
	 * @date: 2018年11月2日 上午9:40:30 
	 * @Description: 上传群舍图片
	 * @param: @param request
	 * @param: @return
	 * @param: @throws Exception 
	 * @return: Attachment
	 * @throws:
	 */
    @Transactional(readOnly = false)
    public Attachment uploadPenImg(HttpServletRequest request) throws Exception {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file == null) {
                    throw new Exception("上传失败：文件为空");    
                }
                if(file.getSize() > 10000000) {
                    throw new Exception("上传失败：文件大小不能超过10M");            
                }
                String name = file.getName();
                String tblId = file.getOriginalFilename().split(",")[0];
                String fileType = file.getOriginalFilename().split(",")[1];
                String tableName = file.getOriginalFilename().split(",")[2];
                if(file.getSize() > 0){
                    String rootPath = Global.getConfig("filePath") + File.separator + "birds" + File.separator + tableName;
                    // 获取到图片在本地处理
                    File targetFile = new File(rootPath, name);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    try {
                        file.transferTo(targetFile);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // 通过谷歌的工具压缩图片
                    // CompressImgUtil.googleCompress(targetFile.getAbsolutePath(), targetFile.getAbsolutePath());
                } else {
                    throw new Exception("上传失败：上传文件不能为空");
                }
                
                Attachment atta = new Attachment();
                atta.setTableId(tblId);
                atta.setTableName(tableName);
                atta.setFileName(name);
                atta.setFileSize(String.valueOf(file.getSize()));
                atta.setFileType(fileType);
                atta.setFilePath(File.separator + "birds" + File.separator + tableName + File.separator + name);
                this.save(atta);
                return atta;
            }
        }
        return null;
    }
    
    /**
	 * 
	 * @Title: upload
	 * @author qjc
	 * @date 2018年4月12日 上午11:03:46
	 * @Description: 文件上传
	 * @param file
	 * @param tblId
	 * @param tblName
	 * @param request
	 * @param status
	 * @throws Exception
	 * 设定文件
	 * @return Attachment 返回类型
	 * @throws
	 */
	@ResponseBody
	@Transactional(readOnly = false)
	public Attachment upload(MultipartFile file, String tblId, String tblName,String type, HttpServletRequest request, Long status) throws Exception {
		// 相对路径
		String destDir = File.separator + "birds" + File.separator  + tblName;
		Attachment att = new Attachment();
		try {
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
			if (file.getSize() > getAllowSize()) {
				throw new Exception("您上传的文件大小已经超出范围");
			}
			String realPath = Global.getConfig("filePath");
			File destFile = new File(realPath + destDir);
			if (!destFile.exists()) {
				destFile.mkdirs();
			}
			String fileNameNew = getFileNameNew() + "." + suffix;
			File f = new File(destFile.getAbsoluteFile() + File.separator + fileNameNew);
			file.transferTo(f);
			f.createNewFile();
			att.setTableId(tblId);
			att.setTableName(tblName);
			att.setFilePath(destDir + File.separator + fileNameNew);
			att.setFileName(file.getOriginalFilename());
			att.setFileType(type);
			save(att);
		} catch (Exception e) {
			throw e;
		}
		return att;
	}
	/***
	 * @Author mengying
	 * @Description 企业审核页附件
	 * @Date  8:52 2019/6/6
	 * @Param id
	 * @return List<Attachment>
	 **/
	public List<Attachment> attachmentList (String tableId,String tableName){
		return attachmentDao.attachmentList(tableId,tableName);
	}

	/***
	 * @Author zhangxingliang
	 * @Description base64转文件存储到服务器
	 * @Date 18:21 2019/6/4
	 * @Param [attachmentList, table_id, tableName]
	 * @return java.lang.String
	 **/
	@ResponseBody
	@Transactional(readOnly = false)
	public String base64SaveFile(List<Attachment> attachmentList, String table_id, String tableName) throws Exception {
		for (Attachment attachment : attachmentList) {
			//delete image and data
			if(StringUtils.isBlank(attachment.getFileName()) && StringUtils.isNotBlank(attachment.getId())){
				this.delete(attachment);
				continue;
			}

			if (StringUtils.isBlank(attachment.getFileName())
			|| (StringUtils.isBlank(attachment.getFile()) && StringUtils.isBlank(attachment.getId()))
			) {
				continue;
			}
			if( StringUtils.isNoneBlank(attachment.getFile()) ) {
				String data = "";
				String dataprefix = "";
				String[] str = attachment.getFile().split("base64,");
				dataprefix = str[0];
				data = str[1];
				String suffix = "";
				if("data:image/jpeg;".equalsIgnoreCase(dataprefix)){//编码的jpeg图片数据
					suffix = ".jpg";
				} else if("data:image/png;".equalsIgnoreCase(dataprefix)){//编码的png图片数据
					suffix = ".png";
				}else{
					throw new Exception("上传图片格式不合法");
				}
				String newFileName = String.valueOf(attachment.getFileName()) + suffix;
				String path = File.separator + tableName + File.separator + newFileName;
				try {
					String realPath = Global.getConfig("filePath");
					File destFile = new File(realPath + File.separator + tableName);
					if (!destFile.exists()) {
						destFile.mkdirs();
					}
					byte[] bs = Base64Utils.decodeFromString(data);
					FileOutputStream out = new FileOutputStream(new File(destFile.getAbsoluteFile()  + File.separator + newFileName));//这里就是文件上传的路劲
					out.write(bs);
					out.flush();
					out.close();
					attachment.setFilePath(path);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			if ("".equals(attachment.getId())) {
				attachment.setIsNewRecord(true);
				attachment.setId(IdGen.nextId());
			}
			attachment.setTableId(table_id);

			attachment.setTableName(tableName);
			this.save(attachment);
		}
		return "";
	}

	/**
	 *
	 * @Title: invoicePhotoView
	 * @author: sy
	 * @date: 2019年06月14日 9:37
	 * @Description: 根据表id和表名称查询发票图片url
	 * @param tblId
	 * @param tblName
	 * @return: java.lang.String
	 */
    public String invoicePhotoView(String tblId, String tblName,String type) {
    	if(StringUtils.isBlank(tblId)||StringUtils.isBlank(tblName)){
			return "";
		}
    	String url = dao.invoicePhotoView(tblId,tblName,type);
    	if(StringUtils.isNotBlank(url)){
			return Global.getConfig("domain")+url;
		}
			return "";
    }

	/**
	 * @author Zhang Xingliang
	 * @description 判断是否上传免疫现场照片/免疫记录表照片， 抗体监测报告 进行提交疫苗补助验证
	 * @date 20:24 2019/6/22
	 * @params [attachment]
	 * @return java.lang.Integer
	 **/
    public Integer findAttachmentCnt(Attachment attachment){
		return this.dao.findAttachmentCnt(attachment);
	}

	/**
	 * @author Zhang Xingliang
	 * @description 批量保存附件 TODO 优化成批量插入sql
	 * @date 9:10 2019/6/25
	 * @params [attachmentList, tableId, tableName, IsNewRecord]
	 * @return void
	 **/
	@Transactional(readOnly = false)
	public void save(List<Attachment> attachmentList,String tableId,String tableName,boolean IsNewRecord) {
		for (Attachment attachment : attachmentList) {
			// delete:记录和七牛图片  deleteFile:只删除七牛图片 deleteData:只删除记录
			if (IsNewRecord || StringUtils.isBlank(attachment.getId()) || "-1".equals(attachment.getId())) {
				attachment.setIsNewRecord(true);
				attachment.setId(IdGen.nextId());
				if(StringUtils.isNotBlank(attachment.getFileType()) && EnumProperty.Attachment.DELETE.getKey().equals(attachment.getFileType()) ){
					this.deleteQiniu(attachment);
					continue;
				}
			}
			//删除前先判断是否存在多条记录(七牛云文件)
			if(StringUtils.isNotBlank(attachment.getFileType()) && EnumProperty.Attachment.DELETE.getKey().equals(attachment.getFileType()) ){
				this.deleteQiniu(attachment);
				continue;
			}
			attachment.setTableId(tableId);
			attachment.setTableName(tableName);
			this.save(attachment);
		}
	}
}